package org.jwt.oauth.config;

import java.util.ArrayList;
import java.util.List;

import org.jwt.oauth.properties.FusionTokenProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.security.oauth2.provider.token.TokenEnhancerChain;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;

@Configuration
@EnableAuthorizationServer
public class FusionTokenServerConfig extends AuthorizationServerConfigurerAdapter {

	@Autowired
	private TokenStore tokenStore;
	@Autowired
	private FusionTokenProperties tokenConfigProperties;
	@Autowired
	private JwtAccessTokenConverter jwtAccessTokenConverter;
	@Autowired
	private JwtTokenEnhancer jwtTokenEnhancer;

	@Override
	public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
		clients
			// 内村存储
			.inMemory()
			// clientId 配置文件里面的配置就失效
			.withClient(tokenConfigProperties.getUsername())
			// clientSecret 配置文件里面的配置就失效
			.secret(tokenConfigProperties.getPassword())
			// 支持的认证方式
			.authorizedGrantTypes("authorization_code", "client_credentials", "refresh_token", "password",
					"implicit")
			// token有效时间
			.accessTokenValiditySeconds(tokenConfigProperties.getAccessTokenTime())
			// refreshToken的有效时间
			.refreshTokenValiditySeconds(tokenConfigProperties.getRefreshTokenTime()).scopes("all");
	}

	@Override
	public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
		security.tokenKeyAccess("isAuthenticated()");
	}

	@Override
	public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
		endpoints.tokenStore(tokenStore);
		endpoints.accessTokenConverter(jwtAccessTokenConverter);
		endpoints.tokenEnhancer(initTokenEnhancerChain());
	}

	public TokenEnhancerChain initTokenEnhancerChain() {
		TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
		List<TokenEnhancer> list = new ArrayList<>();
		list.add(jwtTokenEnhancer);
		list.add(jwtAccessTokenConverter);
		tokenEnhancerChain.setTokenEnhancers(list);
		return tokenEnhancerChain;
	}

}
